<?php
namespace Admin\Controller;
use Think\Controller;
use Admin\Common\Api\UserApi;
use Admin\Common\POMNetTools;
use Admin\Common\POMVIPClient;
use Admin\Common\Excel;
class OrderController extends BaseController {
    private $adminUser = null;
    public function _initialize(){
    	parent::_initialize();
    	$this->adminUser = new UserApi();

    }
	//获取后台管理员的信息
    public function index(){

      $this->display();
    }

   public function OrderList(){
          $title =I('request.title','','trim');
        if(!empty($title)){
           $where['order_sn | source_order_sn'] =array('like',"%{$title}%");
           // print_r($_where);exit;
           // $_where['parcelname']=array('like',"%{$keywords}%");
        }

          $consignee =I('request.consignee','','trim');
        if(!empty($consignee)){
           $where['consignee'] =array('like',"%{$consignee}%");
        }
       $tel =I('request.tel','','trim');
        if(!empty($tel)){
           $where['mobile'] =array('like',"%{$tel}%");
        }
        $start_time = I('request.start_time','','trim');
        $end_time = I('request.end_time','','trim');

        //如果两个为空，没有条件
        //否则 一个为空，一个有值，两个有值
        if(!(empty($start_time) && empty($end_time))){
            $start_time = empty($start_time)?date("Y-m-d"):$start_time;
            $end_time = empty($end_time)?date("Y-m-d"):$end_time;
            if($start_time>$end_time){
                 $temp=$end_time;
                 $end_time=$start_time;
                 $start_time=$temp;
            }

         $start_time = strtotime($start_time);
         $end_time = strtotime($end_time);
          $where['create_time'] = array(between,array($start_time,$end_time));
           // $str =" and create_time between '".time($start_time)."' and '".time($end_time)."'";
        }
         $where['isbigorder'] = 0;
        /* $where['source_order_sn'] = array('exp','is not null');*/
        $_where_order_field["listrows"] =I("request._listrows");
        $_where_order_field["where"] = $where;
        $_where_order_field["field"] = '*';
        $_where_order_field["order"] = 'order_id desc';
        $_datalist= $this->_getListsFromModel('order_info',$_where_order_field);
        foreach ($_datalist['lists'] as $key => $value) {
            $value['new_address'] = "";
            if(!empty($value['country'])){
                $value['new_address'] =$value['country'].'/';
            }
            if(!empty($value['province'])){
                $value['new_address'] .=$value['province'].'/';
            }
            if(!empty($value['city'])){
                $value['new_address'] .=$value['city'].'/';
            }
            if(!empty($value['district'])){
                $value['new_address'] .=$value['district'].'/';
            }
            if(!empty($value['sign_building'])){
                $value['new_address'] .=$value['sign_building'].'</br>';
            }
            if(!empty($value['address'])){
                $value['new_address'] .=$value['address'];
            }
           $_datalist['lists'][$key] = $value;
        }
        $array =array('待发货','已取消','已发货');
        // print_r($_datalist['page_html']);exit;
        $this->assign('array',$array);
        $this->assign('lists',$_datalist);
        $this->display();
   }




   //出入库详情
public function OrderGoodsDetails(){
  $delivery_id = I('request.order_id','','trim');
  $this->assign('order_id',$delivery_id);
  $this->display('goods_details');

}


public function OrderGoodsDetailsList(){
  $order_id = I('request.order_id','','trim');
  $where['order_id'] = $order_id;
   $_where_order_field["listrows"] =I("request._listrows");
        $_where_order_field["where"] = $where;
        $_where_order_field["field"] = '*';
        $_where_order_field["order"] = 'id desc';

        $_datalist= $this->_getListsFromModel('order_item',$_where_order_field);
        foreach ($_datalist['lists'] as $key => $value) {
           $sum += Number_format($value['quantity']*$value['goods_price'], 2, '.','');
        }
        $this->assign('sum_price',$sum);
        $this->assign('lists',$_datalist);


       $this->display('goods_details_list');
}


   //导出excel
   public function export_excel(){
          $title =I('request.title','','trim');
        if(!empty($title)){
           $where['order_sn | source_order_sn'] =array('like',"%{$title}%");
           // print_r($_where);exit;
           // $_where['parcelname']=array('like',"%{$keywords}%");
        }
          $consignee =I('request.consignee','','trim');
        if(!empty($consignee)){
           $where['consignee'] =array('like',"%{$consignee}%");
        }
       $tel =I('request.tel','','trim');
        if(!empty($tel)){
           $where['tel'] =array('like',"%{$tel}%");
        }
        $start_time = I('request.start_time','','trim');
        $end_time = I('request.end_time','','trim');

        //如果两个为空，没有条件
        //否则 一个为空，一个有值，两个有值
        if(!(empty($start_time) && empty($end_time))){
            $start_time = empty($start_time)?date("Y-m-d"):$start_time;
            $end_time = empty($end_time)?date("Y-m-d"):$end_time;
            if($start_time>$end_time){
                 $temp=$end_time;
                 $end_time=$start_time;
                 $start_time=$temp;
            }

         $start_time = strtotime($start_time);
         $end_time = strtotime($end_time);
          $where['create_time'] = array(between,array($start_time,$end_time));
           // $str =" and create_time between '".time($start_time)."' and '".time($end_time)."'";
        }
         $where['isbigorder'] = 0;
      $list = D('order_info')->where($where)->order('create_time desc')->select();
      $data = array(array('序号','订单号','销售系统订单号','金额','收货人','联系电话','收货人地址','下单时间'));
      foreach ($list as $key => $value) {
        $array=array();
            $value['new_address'] = "";
            if(!empty($value['country'])){
                $value['new_address'] =$value['country'].'/';
            }
            if(!empty($value['province'])){
                $value['new_address'] .=$value['province'].'/';
            }
            if(!empty($value['city'])){
                $value['new_address'] .=$value['city'].'/';
            }
            if(!empty($value['district'])){
                $value['new_address'] .=$value['district'].'/';
            }
            if(!empty($value['sign_building'])){
                $value['new_address'] .=$value['sign_building'].'</br>';
            }
            if(!empty($value['address'])){
                $value['new_address'] .=$value['address'];
            }
        array_push($array,$key+1,$value['order_id'],$value['source_order_sn'],$value['order_money'],$value['consignee'],$value['mobile'],$value['new_address'],date('Y-m-d H:i:s',$value['create_time']));
        array_push($data,$array);
      }
       $title = "订单记录".date('Y-m-d H');
      $excel = new Excel();
      header("Content-type:text/html;charset=UTF-8");
      $excel->download($data,$title,'');
   }

 //导入excel
 public function import_excel(){

    if (! empty ( $_FILES ['f'] ['name'] ))
 {
    $tmp_file = $_FILES ['f'] ['tmp_name'];
    $file_name = $_FILES ['f'] ['name'];
    $file_types = explode ( ".", $_FILES ['f'] ['name'] );
    $file_type = $file_types [count ( $file_types ) - 1];
     /*判别是不是.xls文件，判别是不是excel文件*/
     if (strtolower ( $file_type ) != "xls"  )
    {
          $this->error ( '不是Excel文件，重新上传' );
     }

    /*设置上传路径*/
     $savePath = $_SERVER['DOCUMENT_ROOT'] . '/Public/admin/excel/'.date('Y-m-d').'/';
      if (! file_exists ( $savePath )) {
        mkdir ( "$savePath", 0777, true );
    }
    /*以时间来命名上传的文件*/
     // $str = date ( 'Ymdhis' );
     // $file_name = $str . "." . $file_type;
     /*是否上传成功*/
     $file_name=iconv("UTF-8","gb2312", $file_name);
     if (! copy ( $tmp_file, $savePath . $file_name ))
      {
          $this->error ( '上传失败' );
      }
      // print_r($savePath . $file_name);exit;
  // 读取excel
 $filePath = $savePath . $file_name;        //钻石库存文件
 $data = $this->format_excel2array($filePath);
  
 //判断该excel是否能下单
    $fieldArr = $data[1];
    $fieldStr =  implode(',', $fieldArr);

    if(strpos($fieldStr,'订单号') === false || strpos($fieldStr,'商品条形码') == false ||strpos($fieldStr,'收件人') == false){
       $this->error ( '文件字段不符合下单要求' );
    }
   // 组建 下单需要的字段
   unset($data[1]);
   $res = array();
  foreach($data as $key =>$value) {
    if(!empty($value)){
      $res[$value['A']][] = $value;
    }
    

  }
  if(count($res)>20){
     $this->error( '由于系统为稳定，一次下单的数量请不要超过20单' );
  }
 
/*
    $this->assign('list',$data);
    $this->display();*/
  $POMVIPClient = new POMVIPClient();
  $die_order = $succ_order =   array();
//过滤空excel
 foreach ($res as $key => $value) {
     if($key == ""){
        unset($res[$key]);
     }
 }
  foreach ($res as $key => $value) {
    $params = array();
    $params['SourceOrderSn'] = $key;
    if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",$params['SourceOrderSn'])){  //不允许特殊字符
               $dataArr['SourceOrderSn'] = $params['SourceOrderSn'];
               $dataArr['Msg'] =  "该订单号有特殊字符";
               array_push($die_order,$dataArr); 
               continue;
      }
    if($params['SourceOrderSn'] ==""){
               $tmp_str = implode(',', $tmp);
               $dataArr['SourceOrderSn'] = $params['SourceOrderSn'];
               $dataArr['Msg'] = "错误订单";
               array_push($die_order,$dataArr); 
               continue;   
    }
    $goodsArr = $tmp=$num=$goods_code=$goods_list= array();

                   foreach ($value as $k => $v) {
                      //获取每个订单的商品goods_sn
                        $goodsArr[$k]['Quantity'] = $v['C'];

                        $goodsArr[$k]['GoodsSn'] = $POMVIPClient->GetGoodsSnForBarCode($v['B']);

                        $re = D('inventory')->where('goods_sn = "'.$goodsArr[$k]['GoodsSn'].'"')->find();
                        if($v['B'] == ""){
                          $k++;
                           array_push($goods_code,"第".$k."个商品条形码不存在");
                        }
   
                        if( $re == null ){
                           array_push($goods_list,$v['B']);
                        }else{
                           $sum = $re['quantity'] - $re['salenumber'];
                           if($v['C']>$sum){
                             array_push($tmp,$v['B']);
                           }
                        }
                        if($v['C']<=0){
                           array_push($num,'商品'.$goodsArr[$k]['GoodsSn'].'的数量有误');
                        }
                   }

  //条形码为空
     if(!empty($goods_code)){
               $tmp_str = implode(',', $goods_code);
               $dataArr['SourceOrderSn'] = $params['SourceOrderSn'];
               $dataArr['Msg'] =  $tmp_str;
               array_push($die_order,$dataArr); 
               continue;
     }
  //商品不存在
      if(!empty($goods_list)){
               $tmp_str11 = implode(',', $goods_list);
               $dataArr['SourceOrderSn'] = $params['SourceOrderSn'];
               $dataArr['Msg'] =  "商品".$tmp_str11."不存在";
               array_push($die_order,$dataArr); 
               continue;
      }
   //商品库存不足
     if(!empty($tmp)){
               $tmp_str1 = implode(',', $tmp);
               $dataArr['SourceOrderSn'] = $params['SourceOrderSn'];
               $dataArr['Msg'] = "商品".$tmp_str1."库存不足";
               array_push($die_order,$dataArr); 
               continue;
     }
  //商品数量填写错误
    if(!empty($num)){
               $tmp_str2 = implode(',', $num);
               $dataArr['SourceOrderSn'] = $params['SourceOrderSn'];
               $dataArr['Msg'] = $tmp_str2;
               array_push($die_order,$dataArr); 
               continue;
     }
     // 合并商品相同的数量
     $goodsArrNew = $this->merge_quantity($goodsArr) ;
 /*    if($dataArr['SourceOrderSn']){
       continue;
     }*/
     $params['GoodsJsonStr'] = json_encode($goodsArrNew);
     $params['IsTestOrder'] = 'false';
     $params['Consignee'] = $value[0]['E'];
     if($params['Consignee'] ==""){
               $dataArr['SourceOrderSn'] = $params['SourceOrderSn'];
               $dataArr['Msg'] = "该订单收货人为空";
               array_push($die_order,$dataArr); 
               continue;
     }
     $params['Address'] = $value[0]['G'];
     if($params['Address'] ==""){
               $dataArr['SourceOrderSn'] = $params['SourceOrderSn'];
               $dataArr['Msg'] = "该订单收货地址为空";
               array_push($die_order,$dataArr); 
               continue;
     }
     $params['Mobile'] = $value[0]['F'];
     if($params['Mobile'] ==""){
               $dataArr['SourceOrderSn'] = $params['SourceOrderSn'];
               $dataArr['Msg'] = "该订单联系方式为空";
               array_push($die_order,$dataArr); 
               continue;
     }
     $params['IdcardNo'] = $value[0]['H'];
     if($params['IdcardNo'] ==""){
               $dataArr['SourceOrderSn'] = $params['SourceOrderSn'];
               $dataArr['Msg'] = "该订单身份证为空";
               array_push($die_order,$dataArr); 
               continue;
     }
     $params['Remark'] = '';
   if($params['SourceOrderSn'] != "" ){
    //下单操作
    $result = $POMVIPClient->RegularPlaceOrder($params);
  
     $dataArr = array();
    if( false === $result ||  0 != $result["RetCode"])
      {
         $dataArr['SourceOrderSn'] = $params['SourceOrderSn'];
         $dataArr['Msg'] = $result["Message"];
          array_push($die_order,$dataArr);

      }else{

        $dataArr['OrderId'] = $result['OrderId'];
        $dataArr['OrderSn'] = $result['OrderSn'];
        $dataArr['SourceOrderSn'] = $params['SourceOrderSn'];
        array_push($succ_order,$dataArr);
      }
   } 

 }
/*$order_state = array();
$order_state['succ_order'] = $succ_order;
$order_state['die_order'] = $die_order;
*/
/*print_r($die_order);
echo "====";
print_r($succ_order);exit;*/
 $this->assign('die_order',$die_order);
 $this->assign('succ_order',$succ_order);
 $this->assign('die_order_count',count($die_order));
 $this->assign('succ_order_count',count($succ_order));
 $this->display('order_msg_prompt');


  }
}


//将excel商品相同的合并
public function merge_quantity($goodsArr){
    $goodsArrNew= array();
    foreach($goodsArr as $key=>$item)
    {
      //判断是否在标题=>数组索引数组中
    if(isset($goodsArrNew[$item['GoodsSn']]))
    {
      //在的话添加数量
       $goodsArrNew[$item['GoodsSn']]['Quantity'] += $goodsArr[$key]['Quantity'];
    }
    else  
    {
      //不在的话存入映射索引
      $goodsArrNew[$item['GoodsSn']]=$item;
      unset($goodsArr[$key]); //删除原来在数组存在的值
      }
    }
    return array_values($goodsArrNew);
}


public function download_order_excel(){
    $data = array(array('订单号','商品条形码','商品数量','商品名称','收件人','收货人联系方式','收货地址','身份证','下单日期','状态'));
      $title = "excel下单模板";
      $excel = new Excel();
      header("Content-type:text/html;charset=UTF-8");
      $excel->download($data,$title,'');

}


//读取excel
public function format_excel2array($filePath='',$sheet=0){
        Vendor('PHPExcelClasses.PHPExcel','','.php');
        if(empty($filePath) or !file_exists($filePath)){die('file not exists');}
        $PHPReader = new \PHPExcel_Reader_Excel2007();        //建立reader对象
        if(!$PHPReader->canRead($filePath)){
                $PHPReader = new \PHPExcel_Reader_Excel5();
                if(!$PHPReader->canRead($filePath)){
                        echo 'no Excel';
                        return ;
                }
        }

        $PHPExcel = $PHPReader->load($filePath);        //建立excel对象
        $currentSheet = $PHPExcel->getSheet($sheet);        //**读取excel文件中的指定工作表*/
        $allColumn = $currentSheet->getHighestColumn();        //**取得最大的列号*/

        $allRow = $currentSheet->getHighestRow();        //**取得一共有多少行*/
        $data = array();
        for($rowIndex=1;$rowIndex<=$allRow;$rowIndex++){        //循环读取每个单元格的内容。注意行从1开始，列从A开始
                for($colIndex='A';$colIndex<=$allColumn;$colIndex++){
                        $addr = $colIndex.$rowIndex;
                        $cell = $currentSheet->getCell($addr)->getValue();
                        if($cell instanceof PHPExcel_RichText){ //富文本转换字符串
                                $cell = $cell->__toString();
                        }
                        $data[$rowIndex][$colIndex] = $cell;
                }
        }
        return $data;
}


  // TODO: 提交到Bean
public function sub_bean(){
     $order_id =I('request.order_id','','trim');
     $user_id = $_SESSION['admin_user']['id'];
     $POMVIPClient = new POMVIPClient();
     $res = $POMVIPClient->PushOrder($order_id,$user_id);
     if(empty($res)){
          $this->ajaxreturn(array('state'=>1,'msg'=>'同步成功'));exit;
     }
     if($res !=""){
       $this->ajaxreturn(array('state'=>0,'msg'=>$res));exit;
     }
   $this->ajaxreturn(array('state'=>0,'msg'=>'同步失败'));

}
  // TODO: 批量提交到Bean
public function sub_bean_all(){
     $order_ids =I('request.order_ids','','trim');
     $user_id = $_SESSION['admin_user']['id'];
     $order_arr = explode(',', $order_ids);
     $POMVIPClient = new POMVIPClient();
     if(empty($order_arr)){
        $this->ajaxreturn(array('state'=>0,'msg'=>'参数传递错误'));
     }
     $return_succ =  "同步成功的订单有：</br>";
     $return_fail = "同步失败的订单有：</br>";
       foreach ($order_arr as  $value) {
          $res = $POMVIPClient->PushOrder($value,$user_id);
          $array =array();
          if($res==""){
          $return_succ  .= $value.'</br>';
          }else{
           $return_fail  .= $value.'</br>';
          }
       }
  $this->ajaxreturn(array('state'=>1,'msg'=>$return_succ.'</br>'.$return_fail));

}

//上传身份证
public function upload_idcard(){
    $source_order_sn =I('request.source_order_sn','','trim');
    $this->assign('source_order_sn',$source_order_sn);
    $this->display();
}

public function uploadIdrd(){
  $tmp_file_name = $_FILES['file']['tmp_name']; //得到上传后的临时文件
  $_FILES['file']['name']=iconv("UTF-8","gb2312", $_FILES['file']['name']);
    $array = explode('.',$_FILES['file']['name']);

  $file_name = guid().'.'.$array[1]; //源文件

  $file_dir = './Public/idcard/'.date('Y-m-d').'/'; //最终保存目录
  mkdirs($file_dir);
  if(is_dir($file_dir))
  {
  move_uploaded_file($tmp_file_name,$file_dir.$file_name); //移动文件到最终保存目录
  $img_url = $file_dir.$file_name;
    }

    $this->ajaxreturn(array('state'=>1,'url'=> substr($img_url,1)));
}

public function uploadIdrd_http(){
  $data = $_POST['data'];
  $idcard_img = I('request.idcard_img','','trim');
  $idcardanti_img = I('request.idcardanti_img','','trim');
  $idcard =  I('request.idcard','','trim');
  $source_order_sn =  I('request.source_order_sn','','trim');
   $arr=array("idcard"=>$idcard,"idcard_img"=>$idcard_img ,"idcardanti_img"=>$idcardanti_img,"time"=>time());
   $POMVIPClient = new POMVIPClient();
   $a= $POMVIPClient->GetVipInfo();
   $key =$a['KeyCode'];
/*   $key = C('S_key');*/
   $sign=$this->get_sign($arr, $key);
   $row = array();
   $row['data']=json_encode(array("data"=>json_encode($arr),"sign"=>$sign,"key"=> $key));
   // print_r($row);exit;
   $ret= POMNetTools::postData(C('UPLOADIDCARD_URL'),$row);
   $res = array('state'=>0,'msg'=>"身份证上传失败");
   if($ret['RetCode'] ==0 && $ret['Message'] == "Success"){
    $array = $ret['Result'];
    //成功调用接口
     $POMVIPClient = new POMVIPClient();
     $r =$POMVIPClient->PlaceDeliveryIDCardBySn($source_order_sn,$array['IDCodeKey'],$idcard);
    // print_r($r);exit;
      if($r == ""){
         $res = array('state'=>1,'msg'=>"身份证上传成功");
         $this->ajaxreturn($res);exit;
      }
   }
  $this->ajaxreturn($res);exit;


}


function get_sign($data=array(),$key){
   $arr=$data;
   ksort( $arr);
   $str="";
  foreach($arr as $k => $val)
    {
        if(empty($val)) continue;
           $str.=$k.$val;
       }
  $str.=$key;
  $sign=strtoupper(md5($str));
    return $sign;
}
}
